package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/10 23:26
 * @Desc:
 */
@Slf4j
@Aspect
@Component
public class LogAop {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.annotion.MyAnnotion)")
    @Transactional(rollbackFor = Exception.class)
    public Object OperateLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //获取操作者id，通过解析jwt令牌，获取携带的登陆者信息
        Claims claims = Jwts.parser()
                .setSigningKey("itheima")
                .parseClaimsJws(request.getHeader("token"))
                .getBody();
        Integer operateUser = (Integer) claims.get("id");

        //获取操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //获取操作方法类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();

        //获取操作方法名
        String methodName = proceedingJoinPoint.getSignature().getName();

        //获取操作方法参数
        String methodParams = Arrays.toString(proceedingJoinPoint.getArgs());

        //记录原方法开始执行时间
        long startTime = System.currentTimeMillis();

        //调用原方法，并获取操作方法返回值
        Object returnValue = proceedingJoinPoint.proceed();

        //获取原方法执行耗时
        long costTime = System.currentTimeMillis() - startTime;


        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, className, methodName, methodParams,
                String.valueOf(returnValue), costTime);
        operateLogMapper.insert(operateLog);

        log.info("======================================================");
        log.info(operateLog.toString());
        log.info(String.valueOf(claims));
        log.info("======================================================");

        return returnValue;
    }
}
